package com.jie.files.controller;

import com.jie.files.entity.User;
import com.jie.files.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * @author Jeson
 * @description
 * @create 2021/10/4
 * @since 1.0.0
 */
@Controller
@RequestMapping("user")
public class LoginController {

    @Autowired
    private UserService userService;


    @PostMapping("login")
    public String login(User user, HttpSession session){
        User login = userService.findUserByUsernmae(user.getUsername());
        if (login != null) {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(user.getUsername(),user.getPassword()));
            session.setAttribute("user",login);
            return "redirect:/file/showAll";
        }else {
            return "redirect:/index";
        }
    }

    @GetMapping("register")
    public String regst(){
        System.out.println("注册跳转");
        return "register";
    }

    @PostMapping("register")
    public String register(User user, Model model){
        User userByUsernmae = userService.findUserByUsernmae(user.getUsername());
        if(userByUsernmae != null){
            model.addAttribute("massage","用户名已经存在");
            return "register";
        }
        userService.register(user);
        return "redirect:/index";
    }


}